package com.jt.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jt.mapper.DeptMapper;
import com.jt.pojo.*;
import com.jt.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Override
    public List<Dept> getDeptList() {
        List<Dept> list = deptMapper.selectList(null);
        if (list != null && list.size() > 0) {
            return getTree(list);
        }
        return Collections.emptyList();
    }


    private List<Dept> getTree(List<Dept> deptList) {
        List<Dept> oneDept = deptList.stream().filter(a -> a.getParentId().equals("0")).collect(Collectors.toList());
        setSon(deptList, oneDept);
        return oneDept;
    }

    private void setSon(List<Dept> deptList, List<Dept> oneDept) {
        oneDept.forEach(one -> {
            List<Dept> children = deptList.stream().filter(item -> item.getParentId().equals(one.getId())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(children)) {
                one.setChildren(children);
                setSon(deptList, children);
            }
        });
    }

    @Override
    public List<User> getUserListByDeptId() {
        return deptMapper.getUserListByDeptId();
    }

    @Override
    public Result insertUserList(Map<String, Object> map) {
        String deptId = map.get("deptId").toString();
        List<LinkedHashMap> linkedHashMapList = (List<LinkedHashMap>) map.get("userList");
        List<DeptUser> deptUserList =linkedHashMapList.stream().map( userMap -> {
        DeptUser deptUser = new DeptUser();
        deptUser.setDeptId(deptId);
        deptUser.setUserId(userMap.get("id").toString());
        deptUser.setId(UUID.randomUUID().toString());
            return deptUser;
        }).collect(Collectors.toList());
        /*排除已经有的*/
        List<DeptUser> beforeDeptUserList=deptMapper.selectBeforeDeptUserList(deptId);
        List<String> userIds = beforeDeptUserList.stream().map(DeptUser::getUserId).collect(Collectors.toList());
        List<DeptUser> newDeptUserList = deptUserList.stream().filter(deptUser -> {
            return !userIds.contains(deptUser.getUserId());
        }).collect(Collectors.toList());
        if (newDeptUserList.isEmpty() && !deptUserList.isEmpty()){
            return Result.error("已存在此用户");
        }
        Boolean b = deptMapper.insertUserList(newDeptUserList);
        if (b) {
            return  Result.success("添加成功");
        }
        return  Result.error("添加失败");
    }

    @Override
    public boolean removeUser(DeptUser deptUser) {
        return  deptMapper.removeUser(deptUser);
    }

}
